/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/dao/expression/Or.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: Or.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (周一, 02 七月 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.dao.expression;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.elancom.framework.commons.util.CollectionUtils;
import com.elancom.framework.commons.util.ForEach;
import com.elancom.framework.commons.util.JoyfulUtils;

/**
 * @author elancom
 * @date Apr 13, 2012
 */
public class Or implements Condition {
	private static final long serialVersionUID = 5596724612957893551L;

	private final List<Condition> conditiones = new ArrayList<Condition>(8);

	public Or(Condition... conditiones) {
		super();
		CollectionUtils.addArray(this.conditiones, conditiones);
	}

	public Or() {
		super();
	}

	public void or(Condition... conditiones) {
		CollectionUtils.addArray(this.conditiones, conditiones);
	}

	@Override
	public Criterion toCriterion() {
		final Criterion[] criteriones = new Criterion[conditiones.size()];
		JoyfulUtils.forEach(conditiones, new ForEach<Condition>() {
			@Override
			public boolean each(int index, Condition value) {
				criteriones[index] = Restrictions.and();
				return true;
			}
		});

		return Restrictions.or(criteriones);
	}

	@Override
	public String toHQLString() {
		if (conditiones.isEmpty()) {
			return "";
		}

		final StringBuilder sb = new StringBuilder();
		final int size = conditiones.size();

		JoyfulUtils.forEach(conditiones, new ForEach<Condition>() {
			@Override
			public boolean each(int index, Condition value) {
				sb.append(value.toHQLString());
				if (index + 1 != size) {
					sb.append(" or ");
				}
				return true;
			}
		});

		return sb.toString();
	}

	public static void main(String[] args) {
		final Equal e1 = new Equal("userName", true, false);
		final Equal e2 = new Equal("userName", "李四", false);

		final Or or = new Or(e1, e2);
		or.or(new Like("name", "hello"));
		System.out.println(or.toHQLString());
	}
}
